import axios from "axios";
import { message } from 'antd'
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken, removeToken } from "./auth";
//1. 创建axios对象
const service = axios.create({
    baseURL: "/api",
    timeout: 10000,
});

//2. 请求拦截器
service.interceptors.request.use(
    (config) => {
        NProgress.start(); // 请求开始时启动进度条
        let token = getToken();
        if (token) {
            config.headers["token"] = token;
        }
        return config;
    },
    (error) => {
        Promise.reject(error);
    }
);

//3. 响应拦截器
service.interceptors.response.use(
    (response) => {
        NProgress.done(); // 响应成功时结束进度条
        //判断code码
        if (response.status == 200) {
            return {
                data: response.data.data,
                status: response.status,
            };
        } else {
            return response.data;
        }
    },
    (error) => {
        NProgress.done(); // 响应错误时结束进度条
        // console.log("拦截到错误", error);
        if (error.response.data.errorCode === 20000) {

            message.error(error.response.data.msg || "网络错误")
            setTimeout(() => { window.location.href = ('/login') }, 1000)
            removeToken();
        }
        if (error.response.data.errorCode === 40000) {
            message.error('当前是react18+ts实战商城后台管理系统的演示站点，仅供演示，禁止操作')
        }
        return error;
    }
);

export default service;